<template>
  <el-container v-show="open" ref="contact" class="contact">
    <el-main class="contact-left">
      <el-input class="filter-input" placeholder="请输入姓名或号码" size="small" v-model="filterText"></el-input>
      <el-table class="tree-table" ref="tree-table" style="width: 100%;" row-key="nid" :data="filterData"
        height="calc(100% - 0.3vw)" size="small" highlight-current-row cell-class-name="table-cell-custom"
        header-cell-class-name="table-herder-custom" :expand-row-keys="expandKeys" :default-expand-all="expandAll"
        @row-click="rowClick" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column show-overflow-tooltip min-width="120" prop="label" align="left" label="名称">
        </el-table-column>
        <el-table-column prop="deviceTel" label="号码" align="left">
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.type !== 'group'">{{
              deviceStatusLabel(scope.row.deviceTel)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deviceType" label="号码类型" align="center">
          <template slot-scope="scope">
            <span>{{ deviceTypeLabel(scope.row.deviceType) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-aside class="aside-right">
      <div class="label-text">成 员</div>
      <el-scrollbar class="right-scrollbar" wrap-class="right-scrollbar__wrap">
        <div class="join-item" v-for="(row, index) in joinRows" :key="row.nid" @click="deleteRow(index)">
          <div>{{ row.label }}</div>
          <div>{{ row.deviceTel }}</div>
        </div>
      </el-scrollbar>
      <div class="join-footer">
        <el-button @click="handleCommit">确 定</el-button>
      </div>
    </el-aside>
  </el-container>
</template>

<script>
import { mapGetters } from 'vuex'

import deepClone from '@/utils/clone'
import { selectDictLabel } from '@/utils/microsys'

import Webrtc2Sip from '@/utils/Webrtc2Sip'

export default {
  props: {
    open: Boolean,
    meeting: Object,
  },
  data() {
    return {
      deviceTypeOptions: [
        {
          value: 'phone',
          label: '话机',
        },
        {
          value: 'hand_microphone',
          label: '手咪',
        },
        {
          value: 'mobile',
          label: '手机号码',
        },
        {
          value: 'home',
          label: '家庭号码',
        },
        {
          value: 'office',
          label: '办公号码',
        },
        {
          value: 'linkage',
          label: '联动号码',
        },
        {
          value: 'wireless',
          label: '无线终端',
        },
        {
          value: 'fax',
          label: '传真号码',
        },
        {
          value: 'soldier',
          label: '单兵终端',
        },
        {
          value: 'poc',
          label: 'POC终端',
        },
        {
          value: 'video',
          label: '视频终端',
        },
      ],
      // tableData: [], // 表格源数据
      filterText: '', // 查询条件，姓名或号码
      joinRows: [], // 选择的行，只包含号码行，如职员，操作员等
      headerChecked: false, // 表格头部多选框选中状态
      herderIndeterminate: false, // 表格头部多选框半选状态
      expandKeys: [], // 表格默认展开行的rowKeys数组
      expandAll: false,
      filterData: [],
    }
  },
  computed: {
    ...mapGetters({
      tableData: 'userTreeDataToDepart',
      deviceStatusMap: 'deviceStatusMap',
      operatorCallTels: 'operatorCallTels',
      operatorInfo: 'operatorInfo',
    }),
  },
  watch: {
    filterText(val) {
      this.filterTree(val)
    },
  },
  methods: {
    filterTree(filterText) {
      if (!filterText) {
        return (this.filterData = this.tableData)
      }
      let datas = deepClone(this.tableData)

      const filter = (datas, filterText) => {
        for (let i = datas.length - 1; i >= 0; i--) {
          const item = datas[i]
          if (item.type === 'group') {
            filter(item.children, filterText)
            if (item.children.length === 0) {
              datas.splice(i, 1)
            } else {
              this.expandKeys.push(item.nid)
            }
          } else {
            if (
              !item.label.includes(filterText) &&
              !item.deviceTel.includes(filterText)
            ) {
              datas.splice(i, 1)
            } else {
              this.expandKeys.push(item.nid)
            }
          }
        }
      }
      this.expandKeys = []
      filter(datas, filterText)
      this.filterData = datas
    },
    // 获取号码状态
    deviceStatusLabel(deviceTel) {
      const status = this.deviceStatusMap.get(deviceTel)
      return !status || status !== 'offline' ? '在线' : '离线'
    },
    // 号码类型
    deviceTypeLabel(deviceType) {
      return selectDictLabel(this.deviceTypeOptions, deviceType)
    },
    // 单击行
    rowClick(row, column, event) {
      if (row.type === 'group') {
        let rowEl = event.currentTarget
        let expandEls = rowEl.getElementsByClassName('el-table__expand-icon')
        if (expandEls.length > 0) expandEls[0].click()
      } else {
        const status = this.deviceStatusMap.get(row.deviceTel)
        if (status && status === 'offline') {
          return this.$message({
            message: '不要选择离线号码',
            type: 'error',
            duration: 3000,
          })
        } else if (
          !this.joinRows.some((item) => item.deviceTel === row.deviceTel)
        ) {
          this.joinRows.push(row)
        }
      }
    },
    // 删除选中
    deleteRow(index) {
      this.$delete(this.joinRows, index)
    },
    // 确定按钮
    handleCommit() {
      var rows = this.joinRows
      if (rows.length === 0) {
        this.$message({
          message: '请选择数据',
          type: 'error',
          showClose: true,
          duration: 3 * 1000,
        })
        return
      }
      // 添加主叫号码
      var calling = sessionStorage.getItem(
        'meetingCalling-' + this.meeting.meetID
      )
      if (!calling) {
        if (!this.operatorCallTels)
          return this.$message({
            message: '操作员号码不可达',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
        calling = this.operatorCallTels[0]
        sessionStorage.setItem('meetingCalling-' + this.meeting.meetID, calling)
      }
      if (this.operatorCallTels) {
        if (
          rows.length === 1 &&
          this.operatorCallTels.includes(rows[0].obj.defaultNo)
        ) {
          this.$message({
            message: '主被叫号码相同',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
          return
        }
      }

      SDK.getMeetingMember(this.meeting.meetID).then((res) => {
        const members = res.meet_list
        var memberSet = new Set(members.map((value) => value.activeDevice)) // 已进入会议的成员
        var differenceSet = new Set() // 加入会议成员
        for (var i = 0, length = rows.length; i < length; i++) {
          let row = rows[i]
          let obj = row.obj
          if (row.type === 'operator') {
            if (row.id === this.operatorInfo.operatorID) continue
            differenceSet.add(obj.mainTel || viceTel)
          } else if (
            obj.defaultNo &&
            !memberSet.has(obj.defaultNo) &&
            obj.defaultNo !== calling &&
            !this.operatorCallTels.includes(obj.defaultNo)
          ) {
            differenceSet.add(obj.defaultNo)
          }
        }
        let calleds = Array.from(differenceSet)
        if (calleds.length === 0) {
          this.$message({
            message: '被叫号码已在会议中，请重新选择',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
          return
        }
        // 设置webrtc监听事件
        if (Webrtc2Sip.isEnabled()) this.$emit('setWebrtcCostumEvent', calling)
        // 加入会议
        SDK.meetingCall(
          this.meeting.meetID,
          Array.from(differenceSet),
          calling
        ).catch((err) => {
          console.log('加入会议', err)
        })
        this.$store.commit('callFlagEvent', true) // vuex缓存
        this.handleClose()
      })
    },
    // 关闭
    handleClose() {
      this.$emit('update:open', false)
    },

    // 点击外部事件
    clickEvent(e) {
      let box = this.$refs.contact
      let el = box.$el
      if (el && !el.contains(e.target)) {
        this.handleClose()
      }
    },
  },
  mounted() {
    this.filterTree(this.filterText)
    this.$nextTick(() => {
      document.addEventListener('click', this.clickEvent, true)
    })
  },
  destroyed() {
    document.removeEventListener('click', this.clickEvent, true)
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/contact.scss';
</style>
